package com.atguigu.gmall.feign;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lsj
 * @create 2021-08-26 10:29
 */
@Configuration
public class AppFeignConfig {


//    RequestInterceptor headerRequestInterceptorX(){
//        RequestInterceptor interceptor = new RequestInterceptor() {
//            @Override
//            public void apply(RequestTemplate template) {
//                //得到上次的请求
//                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//                HttpServletRequest request = requestAttributes.getRequest();
//
//                //从前面的请求头里面获取到核心信息
//                String userId = request.getHeader("userId");
//                String userTempId = request.getHeader("userTempId");
//                template.header("userId",userId);
//                template.header("userTempId",userTempId);
//            }
//        };
//        return interceptor;
//    }


    /**
     * feign的拦截器，  (上面的另一种写法，因为 RequestInterceptor 是 函数式接口，如下即为labmda表达式的写法)
     *
     * 作用：每次远程发请求的时候，都会尝试给新的request带上请求头
     * @return
     */
    @Bean
    public RequestInterceptor headerRequestInterceptor(){
        return (template)->{
            System.out.println("RequestInterceptor拦截器线程"+Thread.currentThread().getId());
            //如果feign开启线程进行异步调用。这里会获取不到。以前null pointer exception
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if(requestAttributes!=null){
                HttpServletRequest request = requestAttributes.getRequest();
                //从前面的请求头里面获取到核心信息
                String userId = request.getHeader("userId");
                String userTempId = request.getHeader("userTempId");
                template.header("userId",userId);
                template.header("userTempId",userTempId);
            }

        };
    }


}
